package org.kwisatz.nodistun;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.logging.Logger;

class PipeStream extends Thread
{
	static final Logger logger=Logger.getLogger(LocalProxyServer.class.getName());
	private byte[] buffer=new byte[4096];
	private InputStream in;
	private OutputStream out;
	private Runnable closingAction;
	private boolean debug;
	PipeStream(String name, InputStream in, OutputStream out)
	{
		super(name);
		this.in=in;
		this.out=out;
	}

	PipeStream(InputStream in, OutputStream out)
	{
		this.in=in;
		this.out=out;
	}

	public void run()
	{
		try
		{
			int len = in.read(buffer);
			while(len != -1)
			{				
				out.write(buffer, 0, len);
				if(debug)
					System.out.println(getName()+": "+new String(buffer, 0, len));
				len = in.read(buffer);
			}
			logger.info("Pipe "+getName()+" end.");
			if(closingAction != null)
				closingAction.run();
		}
		catch(SocketException ex)
		{
			logger.info("Socket closed in "+getName());
			if(closingAction != null)
				closingAction.run();
		}
		catch (IOException e)
		{			
			e.printStackTrace();
		}
	}
	
	public void setClosingAction(Runnable runnable)
	{
		closingAction=runnable;
	}

	public void setDebug(boolean debug)
	{
		this.debug = debug;
	}
	
}